package com.eastfair.file.service.impl;

import cn.hutool.core.util.StrUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.file.service.FileService;
import com.eastfair.file.vo.FileVO;
import com.eastfair.util.OrderUtil;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.PutObjectResult;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

/**
 * 华为 obs 文件 service.
 *
 * @author dqq
 * @date 2023 /3/3
 */
@Setter
@Slf4j
public class HuaweiObsServiceImpl implements FileService {

    private static final String BUCKET_NAME = "mice-exhibitor";

    @Value("${file.subfix.verify}")
    private Boolean subfixVerify;

    private ObsClient obsClient;

    @Override
    public FileVO uploadFile(MultipartFile multipartFile, String bucketName) throws Exception {
        log.info("localPutFile - 华为Obs文件上传, bucketName={}", bucketName);
        return uploadFile(multipartFile, bucketName, null);
    }

    @Override
    public FileVO uploadFile(MultipartFile multipartFile, String bucketName, String isMobile) throws Exception {
        // 文件扩展名
        String subfix = null;
        // 文件原始名称，不带扩展名
        String rowFilename = null;
        // 文件名
        String originFileName = multipartFile.getOriginalFilename();
        // 系统生成的文件名
        String fileName = OrderUtil.getOrderNo("WJ");
        if (originFileName != null && StrUtil.isNotBlank(originFileName)) {
            subfix = originFileName.lastIndexOf(".") == -1 ? originFileName : originFileName.substring(originFileName.lastIndexOf("."));
            rowFilename = originFileName.lastIndexOf(".") == -1 ? originFileName : originFileName.substring(0, originFileName.lastIndexOf("."));
            fileName = fileName + subfix;
        }
        if (subfixVerify && (StrUtil.isBlank(isMobile) || !"true".equals(isMobile))) {
            // 验证扩展名
            FileService.verifySubFix(subfix);
            // 文件扩展名与文件格式是否一致
            FileService.verifyFileRowSubFix(subfix, multipartFile);
        }
        try (InputStream inputStream = multipartFile.getInputStream()) {
            PutObjectResult putObjectResult = obsClient.putObject(BUCKET_NAME, fileName, inputStream);
            //  返回文件信息
            FileVO fileVO = new FileVO();
            fileVO.setPath(putObjectResult.getObjectUrl());
            fileVO.setFileName(rowFilename);
            fileVO.setSize(multipartFile.getSize() / 1024);
            fileVO.setSubfix(subfix);
            return fileVO;
        } catch (ObsException e) {
            log.error("华为云obs上传失败", e);
            throw BizException.wrap(1001, "华为云obs上传失败");
        }
    }
}